<?php


namespace App\Admin\Controllers\config\forms;


use App\Common\statement\CommonStatement;
use App\Models\config\Config;
use Encore\Admin\Widgets\Form;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class Base extends Form
{
    /**
     * The form title.
     *
     * @var string
     */
    public $title = '基础配置';

    private $module = 'base';

    /**
     * Handle the form request.
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request)
    {
        $post = $request->post();

        foreach ($request->file() as $k =>  $files) {
            if (is_array($files)){
                foreach ($files as $key => $file){
                    $post[$k][] = Storage::url($file->store('config'));
                }
            }else{
                $post[$k] = Storage::url($files->store('config'));
            }
        }

        Config::batchSet($this->module, $post);
        admin_toastr('信息修改成功');

        return back();
    }

    /**
     * Build a form here.
     */
    public function form()
    {
        $map['module'] = $this->module;
        $map['status'] = 1;

        $rows = Config::where($map)->orderBy('type','sort')->get();

        foreach ($rows as $k => $v){
            $type = $v['type'];

            if ($v->help){
                $help = '-'.$v->help;
            }else{
                $help = '';
            }

            if ($v->field_type != 0){
                $help.= '-'.CommonStatement::field_type[$v->field_type];
            }

            switch ($type){
                case 'switch':
                    $this->$type($v['name'],$v->title)
                        ->states(CommonStatement::base_switch)
                        ->rules($v['rule'])
                        ->help($v->name.$help);
                    break;
                case 'multipleImage':
                    $v['value'] = explode(',',$v['value']);
                    $this->$type($v['name'],$v->title)
//                        ->removable()
                        ->rules($v['rule'])
                        ->help($v->name.$help);
                    break;
                default:
                    $this->$type($v['name'],$v->title)->rules($v['rule'])->help($v->name.$help);
                    break;
            }

            $this->data[$v['name']] = $v['value'];
        }

    }

    /**
     * The data of the form.
     *
     * @return array $data
     */
    public function data()
    {
        return $this->data;
    }
}
